<template>
  <!-- 头部搜索框 -->
  <div class="mobile-search">
    <input type="text" :value="searchVal" @input="onSearch" @keydown.enter="handleDown">
    <span @click="handleBack">取消</span>
  </div>
    
  <div v-if="!searchVal" class="searchHistory">
    <!-- 搜索历史 -->
    <p class="title" v-show="historyList.length">
      <span>搜索历史</span>
      <van-icon name="delete-o" size="20px" @click="handleMove" />
    </p>
    <!-- 搜索面包屑 -->
    <p class="historyList" v-show="historyList.length">
      <a v-for="(item,index) in historyList" :key="index">{{ item }}</a>
    </p>

    <!-- 搜索主体 -->
    <div>
      <!-- 导航栏 -->
      <div class="scrollWrapper">
        <ul>
          <li v-for="(navItem, index) in searchNavList" :key="index">
            <a :class="isShow === index ? 'active' : ''" @click="handleHighlight({ navItem, index })">{{
              navItem.categoryName }}</a>
            <div v-if="isShow === index" class="slider"></div>
          </li>
        </ul>
      </div>
      <van-divider>
      </van-divider>

      <!-- 列表 -->
      <div class="list" v-for="(item,index) in searchItemList" :key="index">
        <a class="searchList" @click="handleDetail()">
          <span class="num"
          :style="{
            color: index===0?'#ff0b0b':index===1?'#f86442':index===2?'#f8a642':'#e0c8b4',
          }"
          >{{ index+1 }}</span>
          <span class="word">{{ item.word}}</span>
          <span v-if="item.shift === -1" class="iconfont down">&#xe62a;</span>
          <span v-else-if="item.shift === 1" class="iconfont up">&#xe62b;</span>
          <span v-else-if="item.shift === 0" class="iconfont line">&#xe60c;</span>
        </a>
        <van-divider>
        </van-divider>
    </div>
</div>

  </div>

  <!-- 实时搜索页 -->
  <div v-else>
      <div class="rearlCard">
        <WCard :list="albumResultList" :lineNum="1">
        <div class="news"><span class="iconfont icon-yonghukaihu"></span>{{ filterNum(albumResultList[0].tracks) }}</div>
    					<div><span class="iconfont icon-erji"></span>{{ filterNum(albumResultList[0].play) }}</div>
        </WCard>
      </div>
      
        <div class="realList">
          <p v-for="(item, index) in queryResultList" :key="index" @click="handleDetailList()"><em>{{ item.keyword }}</em></p>
        </div>
    </div>
  
</template>

<script setup lang="ts">
import { ref, onMounted,toRaw ,watch,} from 'vue';
import SearchRequest from '@/api/search'
import { SearchNavList ,SearchKeyWordList} from '@/type/paramsType/parmsType'
import {RealTimeCardList,RealTimeList} from '@/type/resType/searchResType'
import filterNum from '@/tools/filterNum';
import WCard from '@/components/w-card/index.vue';
import clearEmpty from "@/tools/clearEmpty";
import history from '@/tools/history'
import { useRouter } from 'vue-router';
const router = useRouter()



onMounted(() => {
  // 调用获取导航数据
  getSearchNav()
  //导航关键字默认调用一次 
  getSearchKeyword(-1)
  // 初始化历史记录列表
  // history.clearHistory()
})


// 导航数据
let searchNavList = ref<SearchNavList>([])
// 导航高亮的标识,默认第一个高亮
let isShow = ref(0)
// 某个搜索分类关键字的列表数据
let searchItemList = ref<SearchKeyWordList>([])


// 获取导航数据的功能函数
async function getSearchNav() {
  try {
    const res = await SearchRequest.getSearchNav()
    searchNavList.value = res.category
  } catch (error) {
    console.log(error);
  }
}

// 点击某个导航高亮显示
function handleHighlight(params: any) {
  if (isShow.value !== params.index) { //如果没有高亮 设置高亮
    isShow.value = params.index
    // 获取所点击搜索分类的ID
    const {navItem} = params
    let id = toRaw(navItem).categoryId
    // 请求对应的数据
    getSearchKeyword(id)
  } else {
    // isShow.value = -1
    isShow.value = params.index
  }
}

// 获取某个搜索分类下的关键字列表数据的功能函数
async function getSearchKeyword(id:number){
  try {
    const res = await SearchRequest.getSearchKeyword(id)
    searchItemList.value = res.hotWordResultList
    // console.log(res);
  } catch (error) {
    console.log(error);
    
  }
}

// 实时搜索功能

// 获取实时搜索关键字数据的功能函数
async function getRealTimeSearch(value:any){
  if (value===null) {
    return
  }
  
  try {
    const res = await SearchRequest.getRealTimeSearch(value)
    // console.log(res);
    
    // console.log(">>>>>>>>>>",res.data.result.albumResultList);
    albumResultList.value = res.data.result.albumResultList
    queryResultList.value = res.data.result.queryResultList
  } catch (error) {
    console.log(error);
    
  }
}
// 获取输入框的值
let searchVal = ref<string>('');
// 头部卡片数据
const albumResultList = ref<RealTimeCardList>([])
// 返回列表数据
const queryResultList = ref<RealTimeList>([])
// 监视搜索框关键字的变化
watch(searchVal,(newSearchVal:string|undefined)=>{
  getRealTimeSearch(newSearchVal)
})
// 搜索
const onSearch = (e:any) => {
  // console.log(e);
  searchVal.value =e.target.value
  getRealTimeSearch(e.data)
};

// 历史搜索数组数据
let arr = JSON.parse(localStorage.getItem("historyList") as string)
let historyList = arr || ref<string[]>([])

// 获取详情页数据的功能函数
// async function getDetailInfo(kw:string){
//     try {
//       const res = await DetailRequest.getSimilarityAlbumList(kw)
//       console.log(res);
      
//     } catch (error) {
//       console.log(error);
      
//     }
// }
  
// 确定搜索
const handleDown = ()=>{
  searchVal.value = clearEmpty(searchVal.value);
  // 清除空格以及是否有值
  if(!searchVal.value) return;
// 判断重复
if(arr.length === 0){
  // 等于0直接添加数据
  arr.push(searchVal.value)
  // console.log('添加成功',arr)
}else{
  // 不等于0
  // 先判断是否重复
  if(arr.includes(searchVal.value)){
    // 有
    // console.log('有',arr)
    return
  }else{
    // 没有
    // console.log('没有',arr)
    if(arr.length<10){
      arr.push(searchVal.value)
      // console.log('没有重复数据，继续添加，当前长度为：',arr.length,'arr:',arr)
    }else{
      arr.shift()
      arr.push(searchVal.value)
      // console.log('长度超过10，删除第一个数据，保留最新数据',arr)
    }
  }
}
  history.setHistory(arr)
  historyList.value = arr

  // 跳转详情页
  // 读取本地数据
  // let localist = JSON.parse(localStorage.getItem('HometoSearch'))
  // console.log(list);
  // let list = toRaw(localist[0])
  // console.log(list);
  
  
  router.push({
    name:'Album',
    path:'/album',
    params:{
      albumId:51886654
    }
  })

}

// 取消按钮
const handleBack = ()=>{
  searchVal.value = ''
  
}

// 删除历史记录
const handleMove = ()=>{
  // 清除本地存储
  history.clearHistory()
  // 读取本地
  let arr =  JSON.parse(localStorage.getItem("historyList") as string)
  historyList.value = arr
  // 更新页面
  location.reload()

}

// 点击搜索某一导航列表跳转
const handleDetail = ()=>{
  router.push({
    name:'Album',
    path:'/album',
    params:{
      albumId:51886654
    }
  })
}

// 点击搜索框显示列表跳转
const handleDetailList = ()=>{
  router.push({
    name:'Album',
    path:'/album',
    params:{
      albumId:51886654
    }
  })
}


</script>

<style scoped lang='less'>
// 搜索框
.mobile-search {
  width: 90%;
  // display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  input {
    height: 25px;
    width: 85%;
    font-size: 14px;
    border: none;
    border-radius: 20px;
    background-color: #f0f0f0;
    padding-left: 5px
  };
  span{
    font-size: 14px;
    padding-left: 10px;
  }
}



::-webkit-scrollbar {
  width: 10px;
}

.searchHistory {
  width: 100%;
  height: 100%;

  .title {
    display: flex;
    -webkit-box-pack: justify;
    justify-content: space-between;
    margin: 10px;
    padding-left: 5px;
    margin-bottom: 0px;

    span {
      font-size: 14px;
    }
  }

  .historyList {
    width: 90%;
    height: 100%;
    margin: auto;

    a {
      display: inline-block;
      padding: 5px 15px;
      margin: 5px 10px 10px 0;
      background-color: #f3f4f5;
      line-height: 30px;
      border-radius: 4px;
      font-size: 16px;
      color: #333;
    }
  }

  .scrollWrapper {
    overflow: auto;
    padding: 10px 0;

    ul {
      white-space: nowrap;

      li {
        display: inline-block;
        padding: 0px 0px 0px 19px;
        font-size: 16px;
        color: #a3a3ac;

        .slider {
          background-color: red;
          height: 5px;
          border-radius: 5px;
        }
      }
    }
  }

  .list {
    .searchList {
      display: flex;
      align-items: center;
      padding: 0 30px 0 15px;
      line-height: 12px;

      .num {
        width: 5px;
        font-size: 20px;
      }

      .word {
        width: 300px;
        padding-left: 20px;
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: #333;
        // text-align: center;
      }
    }
  }

}

.active {
  color: #40404c !important;
  font-size: 20px;
}

.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.down {
  color: #93cc48;
}

.up {
  color: #e44a3b;
}

.line {
  color: #dededf;
}

.realList{
  line-height:40px;
  font-size: 18px;
  width: 90%;
  margin:auto;
}
.rearlCard{
  width: 90%;
  padding-left: 15px;
}
</style>